/**
 * 保存数据(本地、数据库)
 */

const fs = require('fs');

//https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx029c9b44dcf8867f&redirect_uri=http%3A%2F%2Fchentianyu.free.idcfengye.com%2Fwww&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect
const mysql = require('mysql');
const {mysqlMsg} = require('./config');

//数据库连接信息
const connection = mysql.createConnection({
    host:mysqlMsg.host,
    port:mysqlMsg.port,
    user: mysqlMsg.user,
    password: mysqlMsg.password,
    database: mysqlMsg.database
});

connection.connect();

const {getOauthUserInfo} = require('./getOauthAll')
function saveOauthUserInfo(CODE){
    return new Promise(async(resolve,reject)=>{
        let userinfo = await getOauthUserInfo(CODE);
        let yuanUserInfo = userinfo;
        //查看文件是否存在fs.stat
        fs.stat(`./jsonPage/${userinfo.openid}.json`,(err,stats)=>{
            if(stats&&stats.isFile()){
                //文件存在
                fs.readFile(`./jsonPage/${yuanUserInfo.openid}.json`,(err,data)=>{
                    if(err)reject(err);
                    else {

                        data = JSON.parse(data);
                        resolve({data,yuanUserInfo});
                    };
                })
            }else{
                userinfo = JSON.stringify(userinfo)
                let data = Buffer.from(userinfo);
                fs.writeFile(`./jsonPage/${yuanUserInfo.openid}.json`,data,(err)=>{
                    if(err) reject(err);
                    else {
                        let msg = `文件保存成功OF${yuanUserInfo.openid}.json`;
                        resolve({msg,yuanUserInfo})
                    }
                })
            }
        })
    })
}

module.exports = {
    saveOauthUserInfo,
}


